package com.leshua.channel.mpos.common.utils;

import java.util.*;

/**
 * @author devlin
 * @version 1.0
 * @date 2020/4/24 14:23
 */
public class LeshuaXmlUtils {


    /**
     * xml格式错误提示
     *
     * @param errorCode
     * @param errorMsg
     * @return
     */
    public static String errorMsg(String errorCode, String errorMsg) {
        Map<String, String> resultMap = new HashMap<>(4);
        resultMap.put("resp_code", "0");
        //result_code 不为0则为错误
        resultMap.put("result_code", "1");
        resultMap.put("error_msg", errorMsg);
        resultMap.put("error_code", errorCode);
        return mapToXml(resultMap);
    }

    /**
     * xml格式错误提示
     *
     * @param errorMsg
     * @return
     */
    public static String errorMsg(String errorMsg) {
        return errorMsg("-1", errorMsg);
    }

    /**
     * 当成
     *
     * @param map
     * @return
     */
    public static String mapToXml(Map map) {
        StringBuilder xml = new StringBuilder();
        xml.append("<leshua>");
        if (map != null) {
            Set entrySet = map.entrySet();
            for (Iterator iterator = entrySet.iterator(); iterator.hasNext(); ) {
                Map.Entry entry = (Map.Entry) iterator.next();
                addXmlText(entry.getKey(), entry.getValue(), xml);
            }
        }
        xml.append("</leshua>");
        return xml.toString();
    }

    private static void addXmlText(Object key, Object value, StringBuilder paramXml) {
        if (value instanceof List) {
            List list = (List) value;
            for (Iterator iterator = list.iterator(); iterator.hasNext(); ) {
                Object o = iterator.next();
                if (o instanceof Map) {
                    addXmlText(key, o, paramXml);
                } else {
                    paramXml.append("<").append(key.toString().toLowerCase()).append(">")
                            .append("<![CDATA[").append(o).append("]]>")
                            .append("</").append(key.toString().toLowerCase()).append(">");
                }
            }
        } else if (value instanceof Map) {
            Set s = ((Map) value).entrySet();
            paramXml.append("<").append(key.toString().toLowerCase()).append(">");
            for (Iterator irt = s.iterator(); irt.hasNext(); ) {
                Map.Entry e = (Map.Entry) irt.next();
                addXmlText(e.getKey(), e.getValue(), paramXml);
            }
            paramXml.append("</").append(key.toString().toLowerCase()).append(">");
        } else {
            if (value != null)
                paramXml.append("<").append(key.toString().toLowerCase()).append(">")
                        .append("<![CDATA[").append(value).append("]]>")
                        .append("</").append(key.toString().toLowerCase()).append(">");
        }
    }
}
